//
//  CollectionData.m
//  Coco_Music
//
//  Created by 强哥 on 15/7/4.
//  Copyright (c) 2015年 寇广超. All rights reserved.
//

#import "CollectionData.h"
#import "Play.h"


@implementation CollectionData

+(instancetype)shareCollectionData
{
    static CollectionData *data = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        data = [[CollectionData alloc] init];
    });
    return data;
}

-(void)openCollectionData
{
    NSString *file = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    file = [file stringByAppendingPathComponent:@"CollectionData.sqlite"];
    NSLog(@"%@",file);
    self.Queue = [FMDatabaseQueue databaseQueueWithPath:file];
    [self.Queue inDatabase:^(FMDatabase *db) {
        BOOL judge = [db executeUpdate:@"create table if not exists t_Collection(number INTEGER PRIMARY KEY AUTOINCREMENT,song_name TEXT,singer_name TEXT,audition_list blob);"];
        if (judge) {
            NSLog(@"表创建成功");
        }
        else
        {
            NSLog(@"表创建失败");
        }
    }];
}

-(void)insertCollection:(Play *)play
{
    [self.Queue inDatabase:^(FMDatabase *db) {
        //将数组存成二进制流
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:play.audition_list];
        BOOL judge = [db executeUpdate:@"insert into t_Collection( song_name,singer_name,audition_list) values (?,?,?) ",play.song_name,play.singer_name,data];
        
        if (judge) {
            NSLog(@"插入成功");
        }
        else
        {
            NSLog(@"插入失败");
        }
    }];
}

-(NSMutableArray *)GetCollection
{
    NSMutableArray *array = [NSMutableArray array];
    [self.Queue inDatabase:^(FMDatabase *db) {
        //取出也一样
        FMResultSet *result = [db executeQuery:@"select * from t_Collection;"];
        while ([result next]) {
            NSString *song_name = [result stringForColumn:@"song_name"];
            NSString *singer_name = [result stringForColumn:@"singer_name"];
            NSData *arra = [result dataForColumn:@"audition_list"];
            Play *music = [[Play alloc]init];
            music.song_name = song_name;
            music.singer_name = singer_name;
            music.audition_list = [NSKeyedUnarchiver unarchiveObjectWithData:arra];
            [array addObject:music];
            [music release];
        }
    }];
    return array;
}

-(void)deleteCollection:(NSString *)songname
{
    [self.Queue inDatabase:^(FMDatabase *db) {
        
      [db executeUpdate:@"DELETE FROM t_Collection WHERE song_name = ?",songname];
        
    }];
    
    
}







@end
